<template>
  <div>
    <el-button-group>
      <el-button type="primary" :icon="CirclePlus" v-auth="'CreateDept'" @click="formVisible = true"
        >新建部门</el-button
      >
      <el-button type="success" :icon="Refresh" @click="findTreeData">刷新</el-button>
      <el-button type="success" :icon="Download" @click="handleDownload">导出部门</el-button>
    </el-button-group>
    <el-table
      ref="refTable"
      :data="data.tableData"
      style="width: 100%; margin-bottom: 20px"
      row-key="deptId"
      default-expand-all
    >
      <el-table-column prop="deptName" label="部门名称" width="250" />
      <el-table-column prop="deptCode" label="部门编码" width="150" />
      <el-table-column prop="telephone" label="电话" width="150" />
      <el-table-column prop="seq" label="排序" width="120" />
      <el-table-column prop="status" label="状态" width="150">
        <template #default="scope">
          <el-tag v-if="scope.row.status === 0" type="info">禁用</el-tag>
          <template v-else>启用</template>
        </template>
      </el-table-column>
      <el-table-column prop="userCount" label="成员数量" width="120" />
      <el-table-column label="操作">
        <template #default="scope">
          <div class="opera-col">
            <el-link
              v-if="hasFuncKey('DeptUser')"
              plain
              type="success"
              :underline="false"
              :icon="User"
              @click="handleOpenUserList(scope.row)"
            >
              <span class="text">成员</span>
            </el-link>
            <el-link
              v-if="hasFuncKey('CreateDept')"
              plain
              type="primary"
              :underline="false"
              :icon="CirclePlus"
              @click="handleAddChildrenForm(scope.row)"
            >
              <span class="text">新建</span>
            </el-link>
            <el-link
              v-if="hasFuncKey('EditDept')"
              plain
              type="primary"
              :underline="false"
              :icon="Edit"
              @click="handleOpenEditForm(scope.row)"
            >
              <span class="text">修改</span>
            </el-link>
            <el-link
              v-if="hasFuncKey('DeleteDept')"
              plain
              type="danger"
              :underline="false"
              :icon="Remove"
              @click="handleDelete(scope.row)"
            >
              <span class="text">删除</span>
            </el-link>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <Form ref="refForm" v-model:visible="formVisible" :parent-data="data.tableData" @success="findTreeData" />
    <UserList ref="refUserList" v-model:visible="userListVisible" @update="findTreeData"></UserList>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElTable, ElTableColumn, ElTag } from 'element-plus'
import { CirclePlus, Remove, Edit, User, Download, Refresh } from '@element-plus/icons-vue'
import { confirm, export2Excel } from '@/utils'
import { useAuth } from '@/hooks/auth'
import { deptApi } from '@/api/modules/system/dept'
import type { Dept } from '@/api/modules/system/dept'
import Form from './Form.vue'
import UserList from './UserList.vue'

// 获取权限钩子
const { hasFuncKey } = useAuth()

const refTable = ref()
const data = reactive<{ tableData: Dept[] }>({ tableData: [] as Dept[] })

const findTreeData = () => {
  deptApi.findTree().then(resp => {
    if (resp.success) {
      data.tableData = resp.data
    } else {
      ElMessage.error(resp.message)
    }
  })
}

onMounted(() => {
  findTreeData()
})

const refForm = ref()
const formVisible = ref(false)

// 添加修改的窗口
const handleAddChildrenForm = (data: Dept) => {
  formVisible.value = true
  const parent = { status: 1, parentId: data.deptId }
  refForm.value.setFormData(parent)
}

// 打开修改的窗口
const handleOpenEditForm = (data: Dept) => {
  formVisible.value = true
  refForm.value.setFormData(data)
}

// 执行删除操作
const handleDelete = (row: Dept) => {
  let msg = `确定要删除部门[ ${row.deptName} ]吗?`
  if (row.children && row.children.length > 0) {
    msg = `部门[ ${row.deptName} ]存在下级部门，确定全部删除吗?`
  }
  confirm(msg, () => {
    deptApi.delete([row.deptId]).then(resp => {
      if (resp.success) {
        findTreeData()
        ElMessage.success(`部门[ ${row.deptName} ]已删除`)
      } else {
        ElMessage.error(resp.message)
      }
    })
  })
}

//导出
const handleDownload = () => {
  const cols = [
    { label: '部门名称', key: 'deptName' },
    { label: '部门编号', key: 'deptCode' },
    { label: '电话', key: 'telephone' },
    { label: '排序', key: 'seq' },
    { label: '状态', key: 'status' }
  ]
  const dataList: any[] = []
  for (let r = 0; r < data.tableData.length; r++) {
    const deptData: any[] = []
    const dept = data.tableData[r]
    deptData.push(dept.deptName)
    deptData.push(dept.deptCode)
    deptData.push(dept.telephone)
    deptData.push(dept.seq)
    deptData.push(dept.status == 1 ? '启用' : '禁用')
    dataList.push(deptData)
  }
  export2Excel(cols, dataList, '部门')
}

//成员窗口
const refUserList = ref()
const userListVisible = ref(false)
// 打开用户列表窗口
const handleOpenUserList = (data: Dept) => {
  userListVisible.value = true
  refUserList.value.setDept(data)
}
</script>

<style lang="scss" scoped>
:deep(.el-table__header) {
  thead > tr {
    height: 50px;
    & > th {
      background-color: #f5f7fa !important;
    }
  }
}
.opera-col {
  display: flex;
  a {
    margin-right: 10px;
  }
  .text {
    padding: 0 2px;
  }
}
</style>
